package qianfeng.com.meijiadaka.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.lemon.view.RefreshRecyclerView;
import cn.lemon.view.adapter.Action;
import cn.lemon.view.adapter.MultiTypeAdapter;
import qianfeng.com.meijiadaka.R;
import qianfeng.com.meijiadaka.bean.Home_info1;
import qianfeng.com.meijiadaka.bean.Home_infoAll;
import qianfeng.com.meijiadaka.bean.TypeBean;
import qianfeng.com.meijiadaka.interfacebean.HomeData;
import qianfeng.com.meijiadaka.interfacebean.HomeInfo;
import qianfeng.com.meijiadaka.viewholder.DuoImageViewHolder;
import qianfeng.com.meijiadaka.viewholder.ListViewHolder;
import qianfeng.com.meijiadaka.viewholder.TextImageViewHolder;
import qianfeng.com.meijiadaka.viewholder.VideoViewHolder;
import qianfeng.com.meijiadaka.viewholder.ViewPagerHolder;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    @BindView(R.id.recycler_view)
    RefreshRecyclerView mRecyclerView;
    @BindView(R.id.homefragment_ib)
    ImageButton mBtn;
    private String mBaseUri = "http://home.naildaka.com/";
    private String mPathInfo1 = "http://home.naildaka.com/vapi/v4/home";
    private String mPathInfoAll = "http://home.naildaka.com/vapi/v4/home/combinations?uid=null&pageNo=";
    private int mPage=1;
    private AlertDialog mAlertDialog;
    private MultiTypeAdapter mAdapter;
    private List<Home_info1.ResultBean.AdsBean>mAdsBeen;
    private List<Home_info1.ResultBean.CategoriesBean>mCategoriesBeen;
    private Home_info1.ResultBean.ChannelBean mChannelBean;
    private Home_infoAll.ResultBean.VideoBean mVideoBean1;
    private Home_infoAll.ResultBean.VideoBean mVideoBean2;
    private TypeBean mTypeCategoriesBeen;
    private TypeBean mTypeAds;
    private TypeBean mTypePc1;
    private TypeBean mTypePc2;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 == 1) {
                getData1(true);
            }
            if (msg.arg1 == 2) {
               //getData2(true);
            }
            if (msg.arg1 == 3) {
                getData2(false);
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        mAdsBeen=new ArrayList<>();
        mCategoriesBeen=new ArrayList<>();
        mAdapter=new MultiTypeAdapter(getContext());
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRecyclerView.setSwipeRefreshColors(0xFF437845,0xFFE44F98,0xFF2FAC21);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setRefreshAction(new Action() {
            @Override
            public void onAction() {
                loadData1();
            }
        });
        mRecyclerView.setLoadMoreAction(new Action() {
            @Override
            public void onAction() {
                 loadData3();
            }
        });
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                mRecyclerView.showSwipeRefresh();
                loadData1();
            }
        });
    }

    private void loadData3() {
        mTypePc1=null;
        mTypePc2=null;
        mVideoBean1=null;
        mVideoBean2=null;
        new Retrofit.Builder().baseUrl(mBaseUri).
                addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create()).build().create(HomeInfo.class)
                .getData(mPathInfoAll+mPage).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Action1<Home_infoAll>() {
                    @Override
                    public void call(Home_infoAll home_infoAll) {
                        List<Home_infoAll.ResultBean> result = home_infoAll.getResult();
                        mTypePc1 = new TypeBean();
                        mTypePc2 = new TypeBean();
                        mTypePc1.setPicturesBeen(result.get(0).getPictures());
                        mTypePc2.setPicturesBeen(result.get(1).getPictures());
                        mVideoBean1=result.get(0).getVideo();
                        mVideoBean2=result.get(1).getVideo();
                        Message message=Message.obtain();
                        message.arg1=3;
                        mHandler.sendMessage(message);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e("HomeFragment_infoALl", throwable.toString());
                    }
                });
    }

    public void getData1(boolean isRefresh){
            mAdapter.clear();
            mRecyclerView.dismissSwipeRefresh();
            mAdapter.add(ViewPagerHolder.class, mTypeAds);
            mAdapter.add(ListViewHolder.class, mTypeCategoriesBeen);
            mAdapter.add(TextImageViewHolder.class, getTextImageVirualData());
    }
    public void getData2(boolean b){
        if (b) {
            mPage =1;

        } else {
            mPage++;
        }
        mAdapter.add(DuoImageViewHolder.class, mTypePc1);
        mAdapter.add(VideoViewHolder.class,getVideoVirtualData1());
        mAdapter.add(DuoImageViewHolder.class, mTypePc2);
        mAdapter.add(VideoViewHolder.class,getVideoVirtualData2());
        if (mPage >= 10) {
            mAdapter.showNoMore();
        }
    }

    private Home_infoAll.ResultBean.VideoBean getVideoVirtualData2() {
        return mVideoBean2;
    }

    private Home_infoAll.ResultBean.VideoBean getVideoVirtualData1() {
        return mVideoBean1;
    }


    public Home_info1.ResultBean.ChannelBean getTextImageVirualData() {
        return mChannelBean;
    }



    private void loadData2() {
        mTypePc1=null;
        mTypePc2=null;
        mVideoBean1=null;
        mVideoBean2=null;
        new Retrofit.Builder().baseUrl(mBaseUri).
                addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create()).build().create(HomeInfo.class)
                .getData(mPathInfoAll+mPage).subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Action1<Home_infoAll>() {
                    @Override
                    public void call(Home_infoAll home_infoAll) {
                        List<Home_infoAll.ResultBean> result = home_infoAll.getResult();
                        mTypePc1 = new TypeBean();
                        mTypePc2 = new TypeBean();
                        mTypePc1.setPicturesBeen(result.get(0).getPictures());
                        mTypePc2.setPicturesBeen(result.get(1).getPictures());
                        mVideoBean1=result.get(0).getVideo();
                        mVideoBean2=result.get(1).getVideo();
                        Message message=Message.obtain();
                        message.arg1=2;
                        mHandler.sendMessage(message);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Toast.makeText(getContext(),"亲，网络不好",Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void loadData1() {
        mAdsBeen.clear();
        mChannelBean=null;
        mCategoriesBeen.clear();
        new Retrofit.Builder().baseUrl(mBaseUri).
                addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create()).build().create(HomeData.class)
                .getData(mPathInfo1).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Action1<Home_info1>() {
                    @Override
                    public void call(Home_info1 home_info1) {
                        mTypeAds = new TypeBean();
                        mTypeAds.setAdsBeen(home_info1.getResult().getAds());
                        mTypeCategoriesBeen =new TypeBean();
                        mTypeCategoriesBeen.setCategoriesBeen(home_info1.getResult().getCategories());
                        mCategoriesBeen.addAll(home_info1.getResult().getCategories());
                        mChannelBean=home_info1.getResult().getChannel();
                        Message message=Message.obtain();
                        message.arg1=1;
                        mHandler.sendMessage(message);
                        loadData2();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Toast.makeText(getContext(),"亲，网络不好",Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick(R.id.homefragment_ib)
    public void onClick() {//弹出对话框
        View view= View.inflate(getContext(),R.layout.alert_view,null);
        mAlertDialog = new AlertDialog.Builder(getContext()).setView(view)
                .create();
        mAlertDialog.show();
        TextView tv1= (TextView) view.findViewById(R.id.alert_tv1);
        TextView tv2= (TextView) view.findViewById(R.id.alert_tv2);
        TextView tv3= (TextView) view.findViewById(R.id.alert_tv3);
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//打开照相机

            }
        }); tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//打开相册

            }
        }); tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAlertDialog.dismiss();
            }
        });
    }
}
